package uk.ac.manchester.cs.owl.ontologyrepositoryapi;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntology;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyManager;

/**
 * Author: Matthew Horridge<br>
 * The University of Manchester<br>
 * Bio-Health Informatics Group<br>
 * Date: 25/01/2011
 */
public class BioPortalRepositoryEntry extends  OntologyRepositoryEntryImpl {

    private String id;
    private String abbrev;
    private String format;
    private String version;
    private String apiKey;

    public BioPortalRepositoryEntry(OntologyRepository repository, String displayName, String id, String abbrev, String format, String version, String apiKey) {
        super(repository, displayName);
        this.id = id;
        this.abbrev = abbrev;
        this.format = format;
        this.version = version;
        this.apiKey = apiKey;
    }

    public String getId() {
        return id;
    }

    public String getAbbreviation() {
        return abbrev;
    }

    public String getFormat() {
        return format;
    }
    
    public String getVersion() {
    	return version;
    }
    
    public String getSourceURI() {
    	return "http://rest.bioontology.org/bioportal/virtual/download/" + id;
    }

    public boolean isOWLCompatibleFormat() {
        String upperCaseFormat = format.toUpperCase();
        
        return upperCaseFormat.indexOf("OWL") != -1 || upperCaseFormat.indexOf("OBO") != -1;
    }

    public OWLOntology loadOntology(MissingImportsTreatment missingImportsTreatment) throws OWLOntologyCreationException {
        OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
        if(missingImportsTreatment.equals(MissingImportsTreatment.IGNORE)) {
            manager.setSilentMissingImportsHandling(true);
        }
        
        String request = getSourceURI() + "?apikey=" + apiKey;
        IRI requestIRI = IRI.create(request);
        
        return manager.loadOntology(requestIRI);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("RepositoryEntry( ");
        sb.append(id);
        sb.append(" (");
        sb.append(version);
        sb.append(") ");        
        sb.append(format);
        sb.append(" \"");
        sb.append(abbrev);
        sb.append("\" \"");
        sb.append(getDisplayName());
        sb.append("\" )");
        
        return sb.toString();
    }
}
